﻿using System;
using System.Linq;
using System.Collections;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using WebPattern.Core.Logger;

/// <summary>
/// Summary description for BasePage
/// </summary>
public class BasePage : System.Web.UI.Page
{
	#region Delegate & Events
    public delegate void InitControlsLanguageDLG();
    public event InitControlsLanguageDLG InitControlsLanguageEv;
    #endregion
    
    #region Properties
    static readonly log4net.ILog _logger = log4net.LogManager.GetLogger(typeof(System.Web.UI.Page));
    static readonly CustomLog4net _customLogger = new CustomLog4net(_logger);
    /// <summary>
    /// Loger
    /// </summary>
    public log4net.ILog Logger
    {
        get { return _logger; }
    }
    /// <summary>
    /// Custom Logger
    /// </summary>
    public static CustomLog4net CLogger
    {
        get { return _customLogger; }
    }
	/// <summary>
	/// Culture name 
	/// </summary>
	public string CurrentCultureName
	{
        get { if (Session["__currentLanguage"] != null) return Session["__currentLanguage"].ToString(); else return string.Empty; }
	}
    /// <summary>
    /// TRUE -> When site language was changed; FALSE - else;
    /// </summary>
    public bool IsLanguageChanging
    {
        get
        {
            if (Session["__isLanguageChanging"] != null)
            {
                try
                {
                    return Convert.ToBoolean(Session["__isLanguageChanging"]);
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("File :[{0}] -- Triger [{1}] -- Line [{2}] -- Message [{3}]"
                        , "BasePage.cs"
                        , "IsLanguageChanging"
                        , "36"
                        , "Session[\"__isLanguageChanging\"] is not in corect format -- " + ex.Message);
                    return false;
                }
            }
            else
                return false;
        }
    }
	#endregion

    #region Constructors
    /// <summary>
	/// Constructor
	/// </summary>
	public BasePage()
	{
		//
		// TODO: Add constructor logic here
		//
	}
	#endregion

    #region Page Life Cycle
    protected void Page_PreLoad(object sender, EventArgs e)
    {        
        if (InitControlsLanguageEv != null && IsLanguageChanging)
            InitControlsLanguageEv();
    }
    #endregion

	#region Helper Methods

    #region Initialize DDL
    /// <summary>
    /// Load data from enumerator to dropDownList
    /// </summary>
    /// <param name="ddl">DropDownList</param>
    /// <param name="enumerator">Enumerator</param>
    public void InitDropDownList(DropDownList dropDownList, Type enumerator)
    {
        Hashtable ht = GetEnumForBind(enumerator);
        dropDownList.DataSource = ht;
        dropDownList.DataTextField = "value";
        dropDownList.DataValueField = "key";

        dropDownList.DataBind();
    }

    public void InitDropDownList<TEnum>(DropDownList dropDownList) where TEnum : struct
    {
        var hashTable = GetEnumForBind<TEnum>();
        dropDownList.DataSource = hashTable;
        dropDownList.DataTextField = "value";
        dropDownList.DataValueField = "key";

        dropDownList.DataBind();
    }

    private IDictionary<int, string> GetEnumForBind<TEnum>()
    {
        var enumerationType = typeof(TEnum);
        var names = Enum.GetNames(enumerationType);
        var values = Enum.GetValues(enumerationType).OfType<TEnum>().ToArray();

        var dict = new SortedDictionary<int, string>();
        for (int i = 0; i < names.Length; i++)
        {
            // Get the global resource string.
            string resKey = enumerationType.Name + "_" + names[i];
            try
            {
                // Look in the global resource file called MyResource.resx.

                var resource = GetGlobalResourceObject("enums", resKey);
                if (resource == null)
                    throw new Exception("Could not find global resource.");

                dict.Add(Convert.ToInt32(values[i]), (String)GetGlobalResourceObject("enums", resKey));

            }
            catch
            {
                dict.Add(Convert.ToInt32(values[i]), names[i]);
            }
        }

        return dict;
    }

    private Hashtable GetEnumForBind(Type enumeration)
    {
        string[] names = Enum.GetNames(enumeration);
        Array values = Enum.GetValues(enumeration);
        Hashtable ht = new Hashtable();

        for (int i = 0; i < names.Length; i++)
        {
            // Get the global resource string.
            try
            {
                // Look in the global resource file called MyResource.resx.
                string resKey = enumeration.Name + "_" + names[i];

                if ((String)GetGlobalResourceObject("enums", resKey) == null) throw new Exception("Could not find global resource.");
                ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), (String)GetGlobalResourceObject("enums", resKey));
            }
            catch
            {
                ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
            }
        }
        return ht;
    }
    #endregion

	#region Query Helpers
	private string QueryFindFirstNonNull(string[] names)
	{
		if (names == null || names.Length == 0)
		{
			throw new ArgumentException("Should not be null or an empty array", "names");
		}


		//var value = Request[names.FirstOrDefault(r => !string.IsNullOrEmpty(Request[r]))];
		return null;
	}
	public bool ReadQueryInt(string[] names, out int value)
	{
		return int.TryParse(QueryFindFirstNonNull(names), out value);
	}
	public bool ReadQueryInt(string name, out int value)
	{
		return ReadQueryInt(new[] { name }, out value);
	}
	public bool ReadQueryInt(out int value, params string[] names)
	{
		return ReadQueryInt(names, out value);
	}
	public string ModifyUrlQueryString(string name, string value)
	{
		if (Request.QueryString.Count == 0)
		{
			return string.Format("{0}?{1}={2}", Request.RawUrl, Server.UrlEncode(name), Server.UrlDecode(value));
		}
		if (Request.QueryString[name] == null)
		{
			return string.Format("{0}&{1}={2}", Request.RawUrl, Server.UrlEncode(name), Server.UrlEncode(value));
		}
		else
		{
			return Regex.Replace(Request.RawUrl, @"([?&]" + name + ")=[^?&]+", "$1=" + value);
		}
	}
	public bool ReadQueryGuid(string[] names, out Guid value)
	{
		var str = QueryFindFirstNonNull(names);
		try
		{
			value = new Guid(str);
			return true;
		}
		catch { }
		value = default(Guid);
		return false;
	}
	public bool ReadQueryGuid(string name, out Guid value)
	{
		return ReadQueryGuid(new[] { name }, out value);
	}
	#endregion

	#region Resources
	protected string GetLocalResource(string resourceKey)
	{
		try
		{
			return GetLocalResourceObject(resourceKey).ToString();
		}
		catch (Exception ex)
		{
			return string.Format("Value for resource key: '{0}' not found", resourceKey, ex.Message);
		}
	}
	#endregion

	#endregion
}